package cn.wuqingna.legendgem.random

import cn.wuqingna.legendgem.script.ScriptManager
import org.bukkit.entity.Player


class RandomData(val player: Player, var cache: MutableMap<String, String> = mutableMapOf()) {
    val map = mutableMapOf<String, String>()

    init {
        cache.forEach { (t, u) ->
            map[t] = scriptStr(u)
        }
    }

    fun scriptStr(list: MutableList<String>): MutableList<String>{
        val newlist = mutableListOf<String>()
        list.forEach {
            newlist += scriptStr(it)
        }
        return newlist
    }
    fun scriptStr(str: String): String{
        return invoke(str)
    }

    private fun invoke(source: String): String {
        var source = source

        getElements(source).forEach {
            val prefix = it.substring(0, it.indexOf(":"))
            if (getElements(it).isNotEmpty()) {
                getElements(it).forEach {
                    source = source.replaceFirst("{$it}", invoke("{$it}"))
                }
            } else {
                source = source.replaceFirst("{$it}", ScriptManager.map[prefix]?.eval(player, source, cache) ?: source)


            }
            if (getElements(source).isNotEmpty()) {
                getElements(source).forEach {
                    source = invoke(source)
                }
            }
        }
        return source
    }

    private fun getElements(source: String): List<String> {
        var cycle = 0
        val elements = mutableListOf<String>()
        var markIndex = 0
        source.toCharArray().forEachIndexed { index, c ->

            when (c) {
                '{' -> {
                    if (cycle++ == 0) {
                        markIndex = index + 1
                    }
                }

                '}' -> {
                    if (--cycle == 0) {
                        elements += source.substring(markIndex, index)
                        markIndex = 0
                    }
                }
            }

        }
        return elements
    }


}